package com.hdy.oa.web.action.department;

import com.hdy.DBUtils.JDBC;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/dept/*")
public class DeptServlet extends HttpServlet {
    //重写service（doGet，doPost的父类）方法
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String contextPath=request.getContextPath();
        String servletPath= request.getRequestURI();
        if(servletPath.equals(contextPath+"/dept/list")){
            doList(request,response);
        } else if (servletPath.equals(contextPath+"/dept/add")) {
            doAdd(request,response);
        }else if (servletPath.equals(contextPath+"/dept/delete")) {
            doDel(request,response);
        }else if (servletPath.equals(contextPath+"/dept/modify")) {
            doModify(request,response);
        }else if (servletPath.equals(contextPath+"/dept/query")) {
            doQuery(request,response);
        }else if (servletPath.equals(contextPath+"/dept/details")) {
            doDetails(request,response);
        }
    }

    private void doList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        String contextPath = request.getContextPath();
        //document.location.href="请求路径"
        //document.location="请求路径"
        //window.location.href="请求路径"
        //window.location="请求路径"
        out.print("       <!DOCTYPE html>");
        out.print("<html>");
        out.print("	<head>");
        out.print("		<meta charset='utf-8'>");
        out.print("		<title>部门</title>");
        //javascript
        out.print("<script type='text/javascript'>");
        out.print("          function del(No){");
        out.print("      var ok=window.confirm('您是否要删除？');");
        out.print("      if(ok){");
        out.print("          document.location.href='"+contextPath+"/dept/delete?deptNo='+No;");
        //out.print("          alert('删除成功！')");
        out.print("      }");
        out.print("  }");
        out.print("  </script>");

        out.print("	</head>");
        out.print("	<body>");
        out.print("		<div align='center'>");
        out.print("			<h1><font size='200pix' color='blue'>部门</font></h1>");
        out.print("		</div>");
        out.print("		");
        out.print("		<hr>");
        out.print("		<br><br><br>");
        out.print("		<table align='center' border='1pix' width='600pix' height='300pix'>");
        out.print("			<tr>");
        out.print("				<th>序号</th>");
        out.print("				<th>部门编号</th>");
        out.print("				<th>部门名称</th>");
        out.print("				<th>部门位置</th>");
        out.print("				<th>操作</th>");
        out.print("			</tr>");

        Connection connection=null;
        PreparedStatement ps=null;
        ResultSet rs=null;


        try {
            connection= JDBC.getConnection();
            String sql="select * from dept";
            ps=connection.prepareStatement(sql);
            rs= ps.executeQuery();
            int no=1;

            while(rs.next()){
                String deptNo=rs.getString(1);
                String name=rs.getString(2);
                String loc=rs.getString(3);
                out.print("			<tr>");
                out.print("				<td align='center'>"+(no++)+"</td>");
                out.print("				<td align='center'>"+deptNo+"</td>");
                out.print("				<td align='center'>"+name+"</td>");
                out.print("				<td align='center'>"+loc+"</td>");
                out.print("				<td align='center'><a href='"+contextPath+"/dept/details?deptNo="+deptNo+"'>详情</a> &nbsp;" +
                        "<a href='"+contextPath+"/dept/query?deptNo="+deptNo+"&no="+(no-1)+"'>修改</a> &nbsp;" +
                        "<a href='javascript:void(0)' onclick='del("+deptNo+")'>删除</a></td>");
                out.print("			</tr>");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBC.close(connection,ps,rs);
        }

        out.print("			");
        out.print("		</table>");
        out.print("		<br><br><br>");
        out.print("		<hr>");
        out.print("		<a href='"+contextPath+"/add.html'><font size='5cm' color='red'>新增部门</font></a>");
        out.print("	</body>");
        out.print("<html>");
    }
    private void doAdd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String deptNo = request.getParameter("deptNo");
        String dept = request.getParameter("dept");
        String loc = request.getParameter("loc");

        Connection connection=null;
        PreparedStatement ps=null;
        int count=0;

        try {
            connection=JDBC.getConnection();
            String sql="insert into dept(DEPTNO,DNAME,LOC) values (?,?,?);";
            ps=connection.prepareStatement(sql);
            ps.setString(1,deptNo);
            ps.setString(2,dept);
            ps.setString(3,loc);
            count=ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBC.close(connection,ps,null);
        }
        String contextPath = request.getContextPath();
        if(count==1){
            // request.getRequestDispatcher("/dept/list").forward(request,response);
            response.sendRedirect(contextPath+"/dept/list");
        }else{
            //request.getRequestDispatcher("/error.html").forward(request,response);
            response.sendRedirect(contextPath+"/error.html");
        }
    }
    private void doDel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String deptNo = request.getParameter("deptNo");

        Connection connection=null;
        PreparedStatement ps=null;
        int count=0;

        try {

            connection= JDBC.getConnection();
            connection.setAutoCommit(false);
            String sql="delete from dept where DEPTNO=?";
            ps=connection.prepareStatement(sql);
            ps.setString(1,deptNo);
            count=ps.executeUpdate();
            connection.commit();
        } catch (SQLException e) {
            try {
                if(connection!=null){
                    connection.rollback();
                }
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }finally {
            JDBC.close(connection,ps,null);
        }
        String contextPath = request.getContextPath();
        if(count==1){
            // request.getRequestDispatcher("/dept/list").forward(request,response);
            response.sendRedirect(contextPath+"/dept/list");
        }else{
            out.print("alert('删除失败！')");
            //request.getRequestDispatcher("/error.html").forward(request,response);
            response.sendRedirect(contextPath+"/error.html");
        }
    }
    private void doModify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String deptNo = request.getParameter("deptNo");
        String dName = request.getParameter("dName");
        String loc=request.getParameter("loc");
        String contextPath= request.getContextPath();

        Connection connection=null;
        PreparedStatement ps=null;
        int count=0;

        try {
            connection = JDBC.getConnection();
            String sql="update dept set DNAME=?,LOC=? where DEPTNO=?";
            ps=connection.prepareStatement(sql);
            ps.setString(1,dName);
            ps.setString(2,loc);
            ps.setString(3,deptNo);
            count= ps.executeUpdate();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBC.close(connection,ps,null);
        }
        if(count==1){
//            request.getRequestDispatcher("/dept/list").forward(request,response);
            //重定向
            response.sendRedirect(contextPath+"/dept/list");
        }else {
//            request.getRequestDispatcher("/error.html").forward(request,response);
            // 重定向
            response.sendRedirect(contextPath+"/error.html");
        }

    }
    private void doQuery(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Connection connection=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String contextPath=request.getContextPath();
        String deptno = request.getParameter("deptNo");
        String no=request.getParameter("no");

        out.print("       <!DOCTYPE html>") ;
        out.print("<html>");
        out.print("	<head>");
        out.print("		<meta charset='utf-8'>");
        out.print("		<title>部门修改</title>");
        out.print("	</head>");
        out.print("	<body>");
        out.print("		<h1 align='center'><font size='200pix' color='blue'>部门修改</font></h1>");
        out.print("		<hr>");
        out.print("		<br><br><br>");
        out.print("		<form action='"+contextPath+"/dept/modify'' method='POST'>");
        out.print("			<div align='center' >");



        try {
            connection= JDBC.getConnection();
            String sql="select DEPTNO,DNAME,LOC from dept where DEPTNO=?";
            ps= connection.prepareStatement(sql);
            ps.setString(1,deptno);
            rs = ps.executeQuery();

            if(rs.next()){
                String deptNo=rs.getString("DEPTNO");
                String name=rs.getString("DNAME");
                String loc=rs.getString("LOC");

                out.print("                序号<input type='text'  name='no' value='"+no+"' readonly><br><br>");
                out.print("                部门编号<input type='text' name='deptNo' value='"+deptNo+"'readonly><br><br>");
                out.print("                部门名称<input type='text' name='dName' value='"+name+"'><br><br>");
                out.print("                部门位置<input type='text' name='loc' value='"+loc+"'><br><br>");
                out.print("				<span align='center' ><input type='submit' value='修改'></span>");
                out.print("		<span align='center' >");
                out.print("			<input  type='button' value='返回' onclick='window.history.back()'>");
                out.print("		</span>");

            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBC.close(connection,ps, rs);
        }

        ;out.print("			</div>");
        out.print("		");
        out.print("		</form>");
        out.print("		");
        out.print("	</body>");
        out.print("</html>");
    }
    private void doDetails(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Connection connection=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.print("     <!DOCTYPE html>");
        out.print("<html>");
        out.print("	<head>");
        out.print("		<meta charset='utf-8'>");
        out.print("		<title>部门详情</title>");
        out.print("	</head>");
        out.print("	<body>");
        out.print("		<h1 align='center'><span style='color: skyblue; '>部门详情</span></h1>");
        out.print("		<br>");

        String deptno = request.getParameter("deptNo");

        try {
            connection=JDBC.getConnection();
            String sql="select DEPTNO,DNAME,LOC from dept where DEPTNO=?";
            ps= connection.prepareStatement(sql);
            ps.setString(1,deptno);
            rs = ps.executeQuery();

            if(rs.next()){
                String deptNo=rs.getString("DEPTNO");
                String name=rs.getString("DNAME");
                String loc=rs.getString("LOC");

                out.print("		<div align='center'>");
                out.print("			");
                out.print("				<span style='color: purple; '>部门编号："+deptNo+"</span> <br>");
                out.print("				<span style='color: purple; '>部门名称："+name+" </span><br>");
                out.print("				<span style='color: purple; '>部门位置："+loc+" </span><br>");
                out.print("			");
                out.print("		</div>");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBC.close(connection,ps, rs);
        }
        out.print("		<br>");
        out.print("		<hr>");
        out.print("		<div align='center'>");
        out.print("			<input  type='button' value='返回' onclick='window.history.back()'>");
        out.print("		</div>");
        out.print("		");
        out.print("	</body>");
        out.print("</html>");
    }

}
